package com.example.chapter06;

import android.app.AlertDialog;
import android.content.Intent;
import android.net.Uri;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;

import androidx.appcompat.app.AppCompatActivity;

import com.example.chapter06.database.ShoppingDBHelper;
import com.example.chapter06.entity.CartInfo;
import com.example.chapter06.entity.GoodsInfo;
import com.example.chapter06.util.ToastUtil;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

public class ShoppingCartActivity extends AppCompatActivity implements View.OnClickListener {

    private TextView tv_title, tv_count, tv_total_price;
    private LinearLayout ll_cart, ll_empty, ll_content;
    private ShoppingDBHelper mDBHelper;
    // 声明一个购物车中的商品信息列表
    private List<CartInfo> mCartInfoList;
    // 声明一个根据商品编号查找商品信息的映射，把商品信息缓存起来，这样不用每一次都去查询数据库
    private Map<Integer, GoodsInfo> mGoodsMap = new HashMap<>();

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_shopping_cart);

        // 购物车页面：返回、清空购物车、结算购物车、进入购物频道
        findViewById(R.id.iv_back).setOnClickListener(this);
        findViewById(R.id.btn_clear).setOnClickListener(this);
        findViewById(R.id.btn_settle).setOnClickListener(this);
        findViewById(R.id.btn_shopping_channel).setOnClickListener(this);

        tv_title = findViewById(R.id.tv_title);
        tv_title.setText("购物车");
        ll_cart = findViewById(R.id.ll_cart);
        tv_total_price = findViewById(R.id.tv_total_price);

        tv_count = findViewById(R.id.tv_count);
        tv_count.setText(String.valueOf(MyApplication.getInstance().goodsCount));

        ll_empty = findViewById(R.id.ll_empty);
        ll_content = findViewById(R.id.ll_content);

        mDBHelper = ShoppingDBHelper.getInstance(this);
    }

    @Override
    protected void onResume() {
        super.onResume();
        showCart();
    }

    // 展示购物车中的商品列表
    private void showCart() {
        // 移除下面的所有子视图
        ll_cart.removeAllViews();
        // 查询购物车中的商品列表
        mCartInfoList = mDBHelper.queryAllCartInfo();
        if (mCartInfoList.size() == 0) {
            return;
        }
        for (CartInfo cartInfo : mCartInfoList) {
            // 根据商品编号，查询商品数据库中的商品记录
            GoodsInfo goodsInfo = mDBHelper.queryGoodsInfoById(cartInfo.goodsId);
            mGoodsMap.put(cartInfo.goodsId, goodsInfo);

            // 获取布局文件 item_cart.xml 的根视图
            View view = LayoutInflater.from(this).inflate(R.layout.item_cart, null);
            ImageView iv_thumb = view.findViewById(R.id.iv_thumb);
            TextView tv_name = view.findViewById(R.id.tv_name);
            TextView tv_desc = view.findViewById(R.id.tv_desc);
            TextView tv_count = view.findViewById(R.id.tv_count);
            TextView tv_price = view.findViewById(R.id.tv_price);
            TextView tv_sum = view.findViewById(R.id.tv_sum);

            iv_thumb.setImageURI(Uri.parse(goodsInfo.picPath));
            tv_name.setText(goodsInfo.name);
            tv_desc.setText(goodsInfo.description);
            tv_count.setText(String.valueOf(cartInfo.count));
            tv_price.setText(String.valueOf(goodsInfo.price));
            tv_sum.setText(String.valueOf((int) (goodsInfo.price * cartInfo.count)));

            // 给商品行添加长按事件，删除购物车中的商品
            view.setOnLongClickListener(v -> {
                AlertDialog.Builder builder = new AlertDialog.Builder(ShoppingCartActivity.this);
                builder.setMessage("是否从购物车中删除" + goodsInfo.name + "？");
                builder.setPositiveButton("是", (dialog, which) -> {
                    // 移除当前视图
                    ll_cart.removeView(v);
                    // 从购物车中删除该商品（改数据库）
                    deleteGoods(cartInfo);
                });
                builder.setNegativeButton("否", null);
                builder.create().show();
                return true;
            });

            // 给商品行添加点击事件，进入商品详情页面
            iv_thumb.setOnClickListener(v -> {
                Intent intent = new Intent(ShoppingCartActivity.this, ShoppingDetailActivity.class);
                intent.putExtra("goods_id", goodsInfo.id);
                startActivity(intent);
            });

            // 往购物车列表添加该商品行
            ll_cart.addView(view);
        }

        // 刷新购物车中所有商品的总金额、总数量
        refreshTotalPrice();
        showCartInfo();  // 加上这行代码，防止返回购物车页面时商品总数不刷新
    }

    private void deleteGoods(CartInfo cartInfo) {
        MyApplication.getInstance().goodsCount -= cartInfo.count;
        mDBHelper.deleteCartInfoByGoodsId(cartInfo.goodsId);
        // 从购物车中删除该商品
        CartInfo removedCartInfo = null;
        for (CartInfo info : mCartInfoList) {
            if (info.goodsId == cartInfo.goodsId) {
                removedCartInfo = info;
                break;
            }
        }
        mCartInfoList.remove(removedCartInfo);
        // 显示最新的商品总数
        showCartInfo();
        ToastUtil.show(this, "成功从购物车中删除" + mGoodsMap.get(cartInfo.goodsId).name);
        mGoodsMap.remove(cartInfo.goodsId);
        // 刷新购物车中所有商品的总金额
        refreshTotalPrice();
    }

    // 获取购物车的商品总数，以此决定显示：购物车为空的提示 or 购物车商品列表
    private void showCartInfo() {
        tv_count.setText(String.valueOf(MyApplication.getInstance().goodsCount));
        if (MyApplication.getInstance().goodsCount == 0) {
            ll_empty.setVisibility(View.VISIBLE);
            ll_content.setVisibility(View.GONE);
            ll_cart.removeAllViews();
        } else {
            ll_content.setVisibility(View.VISIBLE);
            ll_empty.setVisibility(View.GONE);
        }
    }

    // 重新计算购物车中的商品总金额
    private void refreshTotalPrice() {
        int totalPrice = 0;
        for (CartInfo cartInfo : mCartInfoList) {
            GoodsInfo goodsInfo = mGoodsMap.get(cartInfo.goodsId);
            totalPrice += goodsInfo.price * cartInfo.count;
        }
        tv_total_price.setText(String.valueOf(totalPrice));  // tv_total_price 在 ll_content 中
    }

    @Override
    public void onClick(View v) {
        if (v.getId() == R.id.iv_back) {
            finish();
        } else if (v.getId() == R.id.btn_shopping_channel) {
            // 从购物车跳转到商场页面
            Intent intent = new Intent(this, ShoppingChannelActivity.class);
            intent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
            startActivity(intent);
        } else if (v.getId() == R.id.btn_clear) {
            // 清空购物车
            mDBHelper.deleteAllCartInfo();
            MyApplication.getInstance().goodsCount = 0;
            showCartInfo();
            ToastUtil.show(this, "成功清空购物车");
        } else if (v.getId() == R.id.btn_settle) {
            // 点击结算按钮
            AlertDialog.Builder builder = new AlertDialog.Builder(this);
            builder.setTitle("结算");
            builder.setMessage("支付功能尚未开通，敬请期待！");
            builder.setPositiveButton("确定", null);
            builder.create().show();
        }
    }
}